import { generateId } from '../types/index.js';

/**
 * 示例规则生成器
 * 生成示例规则
 */
export class ExampleRules {
  /**
   * 创建示例规则
   */
  static createExampleRules() {
    return [
      this.createErrorMonitorRule(),
      this.createPerformanceRule(),
      this.createSecurityRule()
    ];
  }

  /**
   * 错误监控规则
   */
  static createErrorMonitorRule() {
    return {
      id: generateId(),
      name: '监控HTTP错误响应',
      description: '监控4xx和5xx错误响应，发送通知',
      enabled: true,
      conditions: [
        {
          value: 'status 包含 4',
          operator: 'contains'
        }
      ],
      actions: [
        {
          type: 'script',
          enabled: true,
          script: `
console.warn('⚠️ 检测到错误响应:');
console.warn('  URL:', req.url);
console.warn('  方法:', req.method);
console.warn('  状态码:', resp ? resp.statusCode : '无响应');
console.warn('  用户代理:', req.headers['user-agent'] || '未知');

// 可以在这里添加发送通知的代码
// await nf.http.post('https://your-webhook-url', {
//   message: \`错误响应: \${req.method} \${req.url} -> \${resp.statusCode}\`,
//   timestamp: new Date().toISOString()
// });
          `
        }
      ],
      createdAt: Date.now(),
      updatedAt: Date.now()
    };
  }

  /**
   * 性能监控规则
   */
  static createPerformanceRule() {
    return {
      id: generateId(),
      name: '慢请求监控',
      description: '监控响应时间超过2秒的请求',
      enabled: false, // 默认禁用
      conditions: [
        {
          value: 'url 包含 /',
          operator: 'contains'
        }
      ],
      actions: [
        {
          type: 'script',
          enabled: true,
          script: `
if (resp && req.timestamp) {
  const duration = Date.now() - req.timestamp;
  
  if (duration > 2000) {
    console.warn('🐌 慢请求检测:');
    console.warn('  URL:', req.url);
    console.warn('  响应时间:', duration, 'ms');
    console.warn('  状态码:', resp.statusCode);
    
    // 记录性能数据
    // await nf.http.post('/api/performance/log', {
    //   url: req.url,
    //   method: req.method,
    //   duration: duration,
    //   statusCode: resp.statusCode,
    //   timestamp: new Date().toISOString()
    // });
  }
}
          `
        }
      ],
      createdAt: Date.now(),
      updatedAt: Date.now()
    };
  }

  /**
   * 安全监控规则
   */
  static createSecurityRule() {
    return {
      id: generateId(),
      name: '安全威胁检测',
      description: '检测可疑的安全威胁请求',
      enabled: false, // 默认禁用
      conditions: [
        {
          value: 'url 包含 script',
          operator: 'contains'
        }
      ],
      actions: [
        {
          type: 'script',
          enabled: true,
          script: `
// 检测可疑模式
const suspiciousPatterns = [
  'script', 'javascript:', 'onload', 'onerror',
  'union select', 'drop table', '../', '..',
  'eval(', 'document.cookie'
];

const url = req.url.toLowerCase();
const body = req.body ? req.body.toLowerCase() : '';

const threats = suspiciousPatterns.filter(pattern => 
  url.includes(pattern) || body.includes(pattern)
);

if (threats.length > 0) {
  console.error('🛡️ 安全威胁检测:');
  console.error('  URL:', req.url);
  console.error('  方法:', req.method);
  console.error('  威胁模式:', threats);
  console.error('  来源IP:', req.clientIp || '未知');
  
  // 发送安全警报
  // await nf.http.post('/api/security/alert', {
  //   type: 'suspicious_request',
  //   url: req.url,
  //   method: req.method,
  //   threats: threats,
  //   clientIp: req.clientIp,
  //   userAgent: req.headers['user-agent'],
  //   timestamp: new Date().toISOString()
  // });
}
          `
        }
      ],
      createdAt: Date.now(),
      updatedAt: Date.now()
    };
  }

  /**
   * 获取示例规则的描述
   */
  static getExampleRulesInfo() {
    return {
      total: 4,
      rules: [
        {
          name: 'API监控规则',
          description: '记录所有API请求的详细信息',
          enabled: true,
          type: 'monitoring'
        },
        {
          name: 'HTTP错误监控',
          description: '监控4xx和5xx错误响应',
          enabled: true,
          type: 'error-monitoring'
        },
        {
          name: '性能监控',
          description: '检测响应时间超过2秒的慢请求',
          enabled: false,
          type: 'performance'
        },
        {
          name: '安全威胁检测',
          description: '检测可疑的安全威胁模式',
          enabled: false,
          type: 'security'
        }
      ]
    };
  }
} 